<?php

class DeployController extends ControllerBase
{

    public function indexAction()
    {
        echo 'index';
    }

    public function zipAction($siteid)
    {
        include APP_PATH . '/library/pclzip.lib.php';
        $zipName = BASE_PATH . '/_site/' . $siteid . '/zip/deploy_' . date("Y_m_d_H_i_s") . '.zip';
        $pclzip  = new PclZip($zipName);
        $siteDir = BASE_PATH . '/_site/' . $siteid . '/public';
        $ret     = $pclzip->create(
            $siteDir,
            PCLZIP_OPT_REMOVE_PATH, $siteDir,
            PCLZIP_OPT_ADD_PATH, 'install'
        );
        if ($ret == 0) {
            $json = ['code' => 1, 'msg' => $pclzip->errorInfo(true)];
        } else {
            $json = ['code' => 0, 'msg' => null];
        }
        $this->response->setJsonContent($json);
        return $this->response;
    }

    public function ftpAction($siteid)
    {
        $path = $this->request->getPost('path');
        $key  = md5($siteid . ':' . $path);
        if ($this->redis->get($key)) {
            $json = ['code' => 1, 'msg' => '上个任务已经在部署了，两个任务的间隔应该在30s以上'];
        } else {
            $this->redis->set($key, time());
            $this->redis->setTimeout($key, 30);
            $data = serialize([$siteid, $path]);
            $this->redis->lPush('deploy', $data);
            $json = ['code' => 0, 'msg' => null];
        }
        $this->response->setJsonContent($json);
        return $this->response;
    }
}
